//
// Created by huayang on 17-8-16.
//

#ifndef FIGHTER_TDSSUTILS_H
#define FIGHTER_TDSSUTILS_H

#include <string.h>

#include "tdss.h"

void PrintHeader(Header* header) {
  std::cout << "--------print header--------" << std::endl;
  char magic[5] = {0};
  memcpy(magic, header->magic, 4);
  magic[4] = '\0';
  std::cout << "magic : " << magic << std::endl;

  char version[5];
  memcpy(version, header->version, 5);
  version[4] = '\0';
  std::cout << "version : " << version << std::endl;

  std::cout << "sections offset : ";
  for (int i = 0; i < kSections; ++i) {
    printf("%p | ", header->section_offsets[i]);
  }
  std::cout << std::endl;
}

void PrintSection(SectionNode* section) {
  std::cout << "--------print section--------" << std::endl;
  //printf("segments_addr : %p\n", section->segments_addr);
  std::cout << "state : " << section->state << std::endl;
}

void PrintSegment(SegmentNode* segment) {
  std::cout << "--------print segment-------- " << std::endl;
  printf("addr %p \n", segment);
  std::cout << "type : " << segment->type << std::endl;
  char ids[kIdCnt + 1];
  memcpy(ids, segment->id, kIdCnt);
  ids[kIdCnt] = '\0';
  std::cout << "id : " << ids << std::endl;

  std::cout << "offset : " << segment->offset << std::endl;
  std::cout << "state : " << segment->state << std::endl;
  std::cout << "total_length : " << segment->total_length << std::endl;
  std::cout << "name_length : " << segment->name_length << std::endl;
}

std::string ReadContent(void* start_addr, const SegmentNode& segment) {
  char ret[segment.total_length + 1];
  char* data_addr = (char*)start_addr + segment.offset;
  memcpy(ret, data_addr, segment.total_length);
  ret[segment.total_length] = '\0';
  return std::string(ret);
}

std::map<std::string, std::string> ParseContent(const std::string& content, const SegmentNode& seg) {
  std::map<std::string, std::string> ret;
  std::string k = content.substr(0, seg.name_length);
  std::string v = content.substr(seg.name_length, seg.total_length - seg.name_length);
  ret.insert(std::make_pair(k, v));
  return ret;
}

#endif //FIGHTER_TDSSUTILS_H
